<template>
  <div class="course-statistics">
    <div class="page-title">
      <img
        src="@/assets/images/school.png"
        alt=""
        style="width: 20px; height: 20px"
      />
      <div style="font-size: 14px; margin-right: 40px">{{ school }}</div>
      <span style="font-size: 14px; display: inline-block">请选择时间：</span>
      <el-date-picker
        style="
          border: 1px solid #e6e6e6;
          height: 28px;
          font-size: 12px;
          color: rgba(179, 179, 179, 1);
          width: 330px;
        "
        v-model="pickerTime"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="handelChange"
      >
      </el-date-picker>
      <el-select
        v-model="fragmentationSelect"
        placeholder="请选择"
        style="width: 80px; margin-left: 16px"
        @change="handelChange"
      >
        <el-option
          v-for="item in fragmentationOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <!-- <el-button v-if="isShowButton" type="primary" @click="chilkAll"
        >预览全部学校数据</el-button
      > -->
    </div>
    <el-row :gutter="20">
      <el-col :span="12" style="margin-bottom: 20px">
        <div class="course-statistics_echarts-item">
          <div class="title">
            <div class="line"></div>
            学生注册量
          </div>
          <Echarts
            ref="myChartStudent"
            id="myChartStudent"
            v-loading="studentLoading"
          />
        </div>
      </el-col>
      <el-col :span="12" style="margin-bottom: 20px">
        <div class="course-statistics_echarts-item">
          <div class="title">
            <div class="line"></div>
            学生课程浏览量
          </div>
          <Echarts ref="myChartView" id="myChartView" v-loading="viewLoading" />
        </div>
      </el-col>
      <el-col :span="12">
        <div class="course-statistics_echarts-item">
          <div class="title">
            <div class="line"></div>
            学生做题量
          </div>
          <Echarts
            ref="myChartAnswer"
            id="myChartAnswer"
            v-loading="answerLoading"
          />
        </div>
      </el-col>
      <el-col :span="12">
        <div class="course-statistics_echarts-item">
          <div class="title">
            <div class="line"></div>
            学生下载试题量
          </div>
          <Echarts
            ref="myChartDownload"
            id="myChartDownload"
            v-loading="downloadLoading"
          />
        </div>
      </el-col>
    </el-row>

    <el-dialog
      title="学校数据预览"
      :visible.sync="schoolDialog"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-table
        ref="filterTable"
        :data="allSchoolData"
        style="width: 100%"
        max-height="500"
      >
        <el-table-column prop="deptName" label="学校名称" width="180">
        </el-table-column>
        <el-table-column prop="userCount" label="学生注册数" width="180">
          <template slot-scope="{ row }">
            <span v-if="row.userCount == null">0</span>
            <span v-else>{{ row.userCount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="userDownloadCount"
          label="学生下载试题量"
          width="150"
        >
          <template slot-scope="{ row }">
            <span v-if="row.userDownloadCount == null">0</span>
            <span v-else>{{ row.userDownloadCount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="userViewCount"
          label="学生课程游览量"
          width="150"
        >
          <template slot-scope="{ row }">
            <span v-if="row.userViewCount == null">0</span>
            <span v-else>{{ row.userViewCount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="userAnswerCount" label="学生答题量" width="150">
          <template slot-scope="{ row }">
            <span v-if="row.userAnswerCount == null">0</span>
            <span v-else>{{ row.userAnswerCount }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportSchoolData"
          >导出为excel</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  postStatisticsStudent,
  postStatisticsView,
  postStatisticsAnswer,
  postStatisticsDownload,
  postSchoolData,
  exportSchool,
} from "@/api/system/statistics";
import Echarts from "./components/echarts.vue";
import { daysInMonth } from "@/utils/ruoyi";
import elementResizeCourse from "element-resize-detector";
import store from "@/store";
const echarType = {
  Student: "学生注册量",
  View: "学生课程浏览量",
  Answer: "学生做题量",
  Download: "学生下载试题量",
};
export default {
  name: "course",
  props: {},
  components: { Echarts },
  data() {
    return {
      // 默认选中当月
      pickerTime: [
        `${this.parseTime(new Date(), "{y}-{m}")}-01 00:00:00`,
        `${this.parseTime(new Date(), "{y}-{m}")}-${daysInMonth()} 23:59:59`,
      ],
      studentLoading: false,
      viewLoading: false,
      answerLoading: false,
      downloadLoading: false,
      timer: null,
      allSchoolData: [],
      schoolDialog: false,
      isShowButton: false,
      fragmentationOptions: [
        {
          value: 3600 * 24 * 365,
          label: "年",
        },
        {
          value: 3600 * 24 * 30,
          label: "月",
        },
        {
          value: 3600 * 24,
          label: "日",
        },
      ],
      fragmentationSelect: 3600 * 24,
      school: "",
    };
  },
  mounted() {
    this.init();
    this.drawEchart();

    this.school = localStorage.getItem("school");
  },
  methods: {
    chilkAll() {
      this.schoolDialog = true;
    },
    init() {
      let erd = elementResizeCourse();
      let that = this;
      this.$nextTick(() => {
        // 设置防抖 100毫秒内div不再发生变化后执行resize事件
        console.log(this.$el, "this.$el");
        erd.listenTo(this.$el, function () {
          if (that.timer) {
            clearTimeout(that.timer);
          }
          that.timer = setTimeout(() => {
            let myEvent = new Event("resize"); // resize是指resize事件
            window.dispatchEvent(myEvent); // 触发window的resize事件
          }, 50);
        });
      });
    },
    async exportSchoolData() {
      const res = await exportSchool({
        startTime: this.pickerTime[0],
        endTime: this.pickerTime[1],
      });

      if (res.code == 200) {
        let url = `https://manage.aikoolearn.com/video-api${res.msg}`;
        const a = document.createElement("a");
        console.log(url, "url");
        a.href = url;
        a.download = "统计数据"; // 下载后文件名
        a.style.display = "none";
        document.body.appendChild(a);
        a.click(); // 点击下载
        document.body.removeChild(a); // 下载完成移除元素
      }
    },
    setChartClass(index) {
      const className = "myChart" + index;
      return className;
    },
    handelChange() {
      this.drawEchart();
    },
    initChart(name, options) {
      this.$refs[`myChart${name}`].initChart({
        options,
      });
    },
    async getStatisticsStudent(date) {
      this.studentLoading = true;
      const { data } = await postStatisticsStudent(date);
      const xData = [];
      const yData = [];
      data.forEach((item) => {
        yData.push(item.count);
        if (this.fragmentationSelect === 3600 * 24) {
          // 年月日格式
          xData.push(this.parseTime(item.timeSlice, "{y}/{m}/{d}"));
        } else if (this.fragmentationSelect === 3600 * 24 * 30) {
          // 年月格式
          xData.push(this.parseTime(item.timeSlice, "{y}/{m}"));
        } else {
          // 默认情况或其他情况，这里可以添加其他格式的处理
          xData.push(this.parseTime(item.timeSlice, "{y}"));
        }
      });

      let options = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        color: ["rgba(64, 158, 255, 1)"],
        legend: {
          show: false,
        },
        grid: {
          top: "10%",
          left: "5%", // grid布局设置适当调整避免X轴文字只能部分显示
          right: "5%", // grid布局设置适当调整避免X轴文字只能部分显示
          bottom: "25%",
        },
        xAxis: {
          type: "category",
          splitLine: {
            lineStyle: {
              color: "#DFDFDF",
              type: "dashed",
            },
          },
          axisLine: {
            show: false,
          },
          axisLabel: {
            color: "#999999",
            fontSize: "12",
          },
          axisTick: {
            show: false,
          },
          data: xData,
        },
        yAxis: {
          type: "value",
          axisLabel: {
            color: "#999999",
            fontSize: "12",
          },

          splitLine: {
            lineStyle: {
              color: "#DFDFDF",
              type: "dashed",
            },
          },
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
        graphic: {
          type: "text", // 类型：文本
          left: "center",
          top: "middle",
          silent: true, // 不响应事件
          invisible: xData.length > 0, // 有数据就隐藏
          style: {
            fill: "#9d9d9d",
            fontWeight: "bold",
            text: "暂无数据",
            fontFamily: "Microsoft YaHei",
            fontSize: "25px",
          },
        },
        dataZoom: [
          {
            show: false,
            start: 0,
            end: 100,
          },
          {
            type: "inside",
            start: 94,
            end: 100,
          },
          {
            show: false,
            yAxisIndex: 0,
            filterMode: "empty",
            width: 30,
            height: "20%",
            bottom: "10%",
            showDataShadow: false,
            left: "93%",
          },
        ],
        series: [
          {
            name: "数据",
            type: "bar",
            symbol: "circle",
            symbolSize: 6,
            barMaxWidth: 30,
            smooth: true,
            label: {
              show: false,
              // color: "#FFFFFF"
            },
            itemStyle: {
              normal: {
                //这里设置柱形图圆角 [左上角，右上角，右下角，左下角]
                barBorderRadius: [4, 4, 0, 0],
              },
            },

            emphasis: {
              focus: "series",
            },
            data: yData,
          },
        ],
      };

      this.initChart("Student", options);
      this.studentLoading = false;
    },
    async getStatisticsView(date) {
      this.viewLoading = true;
      const { data } = await postStatisticsView(date);
      let finallData = [];
      finallData = data.map((item) => {
        if (item.categoryName !== null) {
          return { value: item.count, name: item.categoryName };
        } else {
          return { value: item.count, name: "其他" };
        }
      });
      console.log(finallData, "finallData");
      let options = {
        tooltip: {
          trigger: "item",
        },
        legend: {
          orient: "vertical",
          left: "right",
          itemHeight: "8",
          itemWidth: "8",
          itemStyle: {
            fontSize: 12,
          },
        },
        series: [
          {
            name: "课程游览量",
            type: "pie",
            // radius: "80%",
            center: ["40%", "45%"],
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            data: finallData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      this.initChart("View", options);
      this.viewLoading = false;
    },
    async postSchoolDatas(data) {
      const res = await postSchoolData(data);
      if (res.code == 200) {
        const valuesArray = [];
        for (const key in res.data) {
          valuesArray.push(res.data[key]);
        }
        this.allSchoolData = valuesArray;
      }
    },
    async getStatisticsAnswer(date) {
      this.answerLoading = true;
      const { data } = await postStatisticsAnswer(date);
      const xData = [];
      const yData = [];
      data.forEach((item) => {
        yData.push(item.count);
        if (this.fragmentationSelect === 3600 * 24) {
          // 年月日格式
          xData.push(this.parseTime(item.timeSlice, "{y}/{m}/{d}"));
        } else if (this.fragmentationSelect === 3600 * 24 * 30) {
          // 年月格式
          xData.push(this.parseTime(item.timeSlice, "{y}/{m}"));
        } else {
          // 默认情况或其他情况，这里可以添加其他格式的处理
          xData.push(this.parseTime(item.timeSlice, "{y}"));
        }
      });
      let options = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        color: ["#467BF0", "#3DCE9E"],
        legend: {
          show: false,
        },
        grid: {
          left: "5",
          right: "5",
          top: "65",
          bottom: "20",
          containLabel: true,
        },
        dataZoom: [
          {
            show: false,
            start: 0,
            end: 100,
          },
          {
            type: "inside",
            start: 94,
            end: 100,
          },
          {
            show: false,
            yAxisIndex: 0,
            filterMode: "empty",
            width: 30,
            height: "20%",
            bottom: "10%",
            showDataShadow: false,
            left: "93%",
          },
        ],
        xAxis: {
          type: "category",
          splitLine: {
            lineStyle: {
              color: "#DFDFDF",
              type: "dashed",
            },
          },
          axisLine: {
            show: false,
          },
          axisLabel: {
            color: "#999999",
            fontSize: "12",
          },
          axisTick: {
            show: false,
          },
          data: xData,
        },
        yAxis: {
          type: "value",
          axisLabel: {
            color: "#999999",
            fontSize: "12",
          },
          splitLine: {
            lineStyle: {
              color: "#DFDFDF",
              type: "dashed",
            },
          },
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
        graphic: {
          type: "text", // 类型：文本
          left: "center",
          top: "middle",
          silent: true, // 不响应事件
          invisible: xData.length > 0, // 有数据就隐藏
          style: {
            fill: "#9d9d9d",
            fontWeight: "bold",
            text: "暂无数据",
            fontFamily: "Microsoft YaHei",
            fontSize: "25px",
          },
        },
        series: [
          {
            // name: "数据",
            type: "line",
            itemStyle: {
              normal: {
                borderColor: "#ffff", // 标记的边框颜色
                borderWidth: 2, // 标记的边框宽度
                fill: "none", // 设置填充为无，即空心
              },
            },
            areaStyle: {
              //区域填充渐变颜色
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(179, 216, 255, 1)", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(255, 255, 255, 0)", // 100% 处的颜色
                  },
                ],
                global: false, // 缺省为 false
              },
            },

            symbol: "circle",
            symbolSize: 6,
            barWidth: 30,
            // showSymbol: false,
            smooth: true,
            label: {
              show: false,
              // color: "#FFFFFF"
            },
            emphasis: {
              focus: "series",
            },
            data: yData,
          },
        ],
      };
      this.initChart("Answer", options);
      this.answerLoading = false;
    },
    async getStatisticsDownload(date) {
      this.downloadLoading = true;
      const { data } = await postStatisticsDownload(date);
      const xData = [];
      const yData = [];
      data.forEach((item) => {
        yData.push(item.count);
        if (this.fragmentationSelect === 3600 * 24) {
          // 年月日格式
          xData.push(this.parseTime(item.timeSlice, "{y}/{m}/{d}"));
        } else if (this.fragmentationSelect === 3600 * 24 * 30) {
          // 年月格式
          xData.push(this.parseTime(item.timeSlice, "{y}/{m}"));
        } else {
          // 默认情况或其他情况，这里可以添加其他格式的处理
          xData.push(this.parseTime(item.timeSlice, "{y}"));
        }
      });
      let options = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        color: ["rgba(64, 158, 255, 1)"],
        legend: {
          show: false,
        },
        grid: {
          top: "10%",
          left: "5%", // grid布局设置适当调整避免X轴文字只能部分显示
          right: "5%", // grid布局设置适当调整避免X轴文字只能部分显示
          bottom: "25%",
        },
        xAxis: {
          type: "category",

          axisLine: {
            show: false,
          },
          axisLabel: {
            color: "#999999",
            fontSize: "12",
            // interval: 0,
            // rotate:45
          },
          axisTick: {
            show: false,
          },
          data: xData,
        },
        dataZoom: [
          {
            show: false,
            start: 0,
            end: 100,
          },
          {
            type: "inside",
            start: 94,
            end: 100,
          },
          {
            show: false,
            yAxisIndex: 0,
            filterMode: "empty",
            width: 30,
            height: "20%",
            bottom: "10%",
            showDataShadow: false,
            left: "93%",
          },
        ],
        yAxis: {
          type: "value",
          axisLabel: {
            color: "#999999",
            fontSize: "12",
          },

          splitLine: {
            lineStyle: {
              color: "#DFDFDF",
              type: "dashed",
            },
          },
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
        graphic: {
          type: "text", // 类型：文本
          left: "center",
          top: "middle",
          silent: true, // 不响应事件
          invisible: xData.length > 0, // 有数据就隐藏
          style: {
            fill: "#9d9d9d",
            fontWeight: "bold",
            text: "暂无数据",
            fontFamily: "Microsoft YaHei",
            fontSize: "25px",
          },
        },
        series: [
          {
            name: "数据",
            type: "bar",
            symbol: "circle",
            backgroundStyle: {
              color: "rgba(64, 158, 255, 0.2)",
            },

            showBackground: true,
            symbolSize: 6,
            barMaxWidth: 30,
            // showSymbol: false,
            smooth: true,
            label: {
              show: false,
              // color: "#FFFFFF"
            },
            itemStyle: {
              normal: {
                //这里设置柱形图圆角 [左上角，右上角，右下角，左下角]
                barBorderRadius: [4, 4, 0, 0],
              },
            },
            emphasis: {
              focus: "series",
            },
            data: yData,
          },
        ],
      };

      this.initChart("Download", options);
      this.downloadLoading = false;
    },
    async drawEchart() {
      const date = {
        startTime: this.pickerTime[0],
        endTime: this.pickerTime[1],
        span: this.fragmentationSelect,
        deptId: 138,
      };
      const viewData = {
        startTime: this.pickerTime[0],
        endTime: this.pickerTime[1],
        // span: this.fragmentationSelect,
        deptId: 138,
      };
      this.getStatisticsStudent(date);
      this.getStatisticsView(viewData);
      this.getStatisticsAnswer(date);
      this.getStatisticsDownload(date);
      if (store.getters.roles.includes("admin")) {
        this.isShowButton = true;
        this.postSchoolDatas({
          startTime: this.pickerTime[0],
          endTime: this.pickerTime[1],
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.course-statistics_echarts-item {
  // box-shadow: 0px 0px 8px 0px rgba(0,0,0,0.2);
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e6e6e6;
}
.page-title {
  display: flex;
  align-items: center;
  padding: 0 10px 10px 10px;
}
.course-statistics {
  padding: 20px;
  // height: calc(100vh - 90px);
  width: 100%;

  .el-row {
    height: 100%;
  }
  .title {
    display: flex;
    align-items: center;
  }
  .line {
    width: 4px;
    height: 18px;
    background: #409eff;
    border-radius: 3px;
    margin-right: 8px;
  }
  &_echarts-item {
    height: 310px;
    width: 100%;
  }
}

::v-deep {
  .el-date-editor .el-range-input {
    color: rgba(179, 179, 179, 1);
  }
  .el-date-editor .el-range-separator {
    color: rgba(179, 179, 179, 1);
    font-size: 12px;
    line-height: 20px;
  }
  .el-input--medium .el-input__inner {
    height: 28px;
  }

  .el-range-editor--medium .el-range__icon,
  .el-range-editor--medium .el-range__close-icon {
    line-height: 20px;
  }
  .el-input--medium .el-input__inner {
    font-size: 12px;
    line-height: 20px;
    color: rgba(179, 179, 179, 1);
    width: 58px;
  }
  .el-input__suffix {
    right: 26px;
    top: 5px;
  }
  .el-select .el-input .el-select__caret {
    transform: rotateZ(180deg);
  }
}
</style>
